const fs = require("fs");
const path = require("path")
function getContentType(filePath) {
    //mime类型
    const mime = {
        "gz": "application/x-gzip",
        "zip": "application/zip",
    };
    let ext = path.extname(filePath);
    ext = ext ? ext.slice(1) : 'unknown';
    return mime[ext.toLowerCase()];
}
module.exports = {
    fileWhiter: function (pathStr, fileName, fileBuffer) {
        var filePath = path.join(process.cwd(), pathStr)
        var filePathAll = path.join(process.cwd(), pathStr + "/" + fileName)
        var file = fs.existsSync(filePathAll);
        if (file) {//清空内容
            fs.writeFileSync(filePathAll, "")
        } else {//创建文件夹
            fs.mkdirSync(filePath, { recursive: true });
        }
        fs.writeFileSync(filePathAll, fileBuffer)
    },
    getFileExtname: function (fileName) {
        var rxg = /(\.[\d\D]+){1}/g
        var data = rxg.exec(fileName)
        return data ? data[0] : ""
    },
    getContentType: getContentType,
    fileReadChunk: function (range, filePath, chunkSize = 1024 * 1024 * 100) {
        var fileSize = fs.statSync(filePath).size;
        let contentType = getContentType(filePath);
        let head = {
            code: 200,
            head: {
                'Content-Length': fileSize,
                'content-type': contentType,
            }
        };
        if (range) {
            let parts = range.replace(/bytes=/, "").split("-");
            let start = parseInt(parts[0], 10);
            let end = parts[1] ? parseInt(parts[1], 10) : start + chunkSize;
            end = end > fileSize - 1 ? fileSize - 1 : end;
            chunkSize = (end - start) + 1;
            head = {
                code: 206,
                filePath,
                start,
                end,
                head: {
                    'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                    'content-type': contentType,
                    'Content-Length': chunkSize,
                    'Accept-Ranges': 'bytes'
                }
            }
        }
        return head
    }
}
